#include <stdio.h>
#include <sys/types.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include "file_lock.h"
#include "Debug.h"


int file_lock(const char *szfilename)
{
    extern int errno;
    int fd = open(szfilename, O_WRONLY);   //   O_CREAT
    if(fd < 0)
    {
        Safe_Printf("error open file.%s. errno=%d,%s", szfilename, errno, strerror(errno));
        return -1;
    }
    int nloc = flock(fd, LOCK_EX);
    if(nloc < 0)
    {
        Safe_Printf("error lock file.%s. errno=%d,%s", szfilename, errno, strerror(errno));
        return -1;
    }
    //Safe_Printf("lock succ.%s", szfilename);
    return fd;
}

int file_unlock(int fd)
{
    if(fd < 0)
    {
        printf("error fd=%d",fd);
        return -1;
    }
    int nloc = flock(fd, LOCK_UN);
    if(nloc < 0)
    {
        Safe_Printf("error unlock file. errno=%d,%s", errno, strerror(errno));
        return -1;
    }
    close(fd);
    return 0;
}


// test
#include "file_lock.h"
#include "Debug.h"
void main_testfilelock1()
{
    int fd = 0;
    fd = file_lock("sdf");
    Safe_Printf("lock.%d", fd);

    fd = file_lock("/tmp/sipsettings.xml");
    Safe_Printf("lock.%d", fd);
    file_unlock(fd);
    Safe_Printf("unlock.%d", fd);
    
    fd = file_lock("/tmp/sipsettings.xml");
    Safe_Printf("lock.%d", fd);
    file_unlock(fd);
    Safe_Printf("unlock.%d", fd);

    fd = file_lock("/tmp/sipsettings.xml");
    Safe_Printf("lock.%d", fd);
    file_unlock(fd);
    Safe_Printf("unlock.%d", fd);


    fd = file_lock("/tmp/sipsettings.xml");
    Safe_Printf("lock.%d", fd);
    fd = file_lock("/tmp/sipsettings.xml");
    Safe_Printf("lock.%d", fd);

    exit(0);
}


